<template>
    <div>
        <el-drawer :title="title + '商品信息'" v-model="visible" :before-close="close" size="800px" center destroy-on-close>
            <div v-loading="loading">
                <el-scrollbar max-height="calc(100vh - 170px)">
                    <el-form class="pr10" ref="formRef" :model="formData" label-width="95px" label-position="right"
                        status-icon label-suffix=":">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="商品名称" prop="name"
                                    :rules="[{ required: true, message: '请输入商品名称' }]">
                                    <el-input v-model="formData.name" @change="setQuickCode" maxlength="30" clearable
                                        show-word-limit placeholder="请输入商品名称" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品分类" prop="categoryId"
                                    :rules="[{ required: true, message: '请选择商品分类' }]">
                                    <!-- 商品分类下拉框 -->
                                    <el-select v-model="formData.categoryId" placeholder="请选择商品分类" clearable>
                                        <el-option v-for="item in categoryOptions" :key="item.categoryId"
                                            :label="item.categoryName" :value="item.categoryId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品编码" prop="code"
                                    :rules="[{ required: true, validator: codeValidator, trigger: 'blur' }]">
                                    <el-input v-model="formData.code" maxlength="30" clearable show-word-limit
                                        placeholder="请输入商品编码" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品规格" prop="specsName"
                                    :rules="[{ required: true, message: '请输入商品规格' }]">
                                    <el-input v-model="formData.specsName" maxlength="30" clearable show-word-limit
                                        placeholder="请输入商品规格" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="库存数量" prop="stockNum"
                                    :rules="[{ required: true, message: '请输入库存数量' }]">
                                    <el-input-number v-model="formData.stockNum" :min="0" :max="99999999" :step="1"
                                        placeholder="请输入库存数量" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品单位" prop="unitName"
                                    :rules="[{ required: true, message: '请输入商品单位' }]">
                                    <el-input v-model="formData.unitName" maxlength="30" clearable show-word-limit
                                        placeholder="请输入商品单位" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="销售价格" prop="price"
                                    :rules="[{ required: true, message: '请输入销售价格' }]">
                                    <el-input-number v-model="formData.price" :min="0" :precision="2" :step="0.01"
                                        placeholder="请输入销售价格" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品特价" prop="discountPrice">
                                    <el-input-number v-model="formData.discountPrice" :min="0" :precision="2"
                                        :step="0.01" placeholder="请输入商特价" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="成本价格" prop="cost">
                                    <el-input-number v-model="formData.cost" :min="0" :precision="2" :step="0.01"
                                        placeholder="请输入成本价格" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="获得积分" prop="score">
                                    <el-input-number v-model="formData.score" :min="0" :precision="2" :step="0.01"
                                        placeholder="请输入可获得积分" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品状态" prop="status">
                                    <el-radio-group v-model="formData.status">
                                        <el-radio :value="1" border>上架</el-radio>
                                        <el-radio :value="0" border>下架</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="品牌名称" prop="brand">
                                    <el-input v-model="formData.brand" maxlength="30" clearable show-word-limit
                                        placeholder="请输入商品单位" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品简码" prop="quickCode">
                                    <el-input v-model="formData.quickCode" maxlength="30" clearable show-word-limit
                                        placeholder="请输入商品简码" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品产地" prop="address">
                                    <el-input v-model="formData.address" maxlength="300" clearable show-word-limit
                                        placeholder="请输入商品单位" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="排序号" prop="sort">
                                    <el-input-number v-model="formData.sort" :min="0" :max="99999999"
                                        placeholder="按数字小到大排序" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="备注信息" prop="remark">
                                    <el-input v-model="formData.remark" maxlength="300" clearable show-word-limit
                                        placeholder="备注信息最多200字" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-form-item label="商品主图" prop="imageUrl">
                                <!-- 上传图片组件 -->
                                <el-upload class="avatar-uploader" accept="image/png, image/jpg, image/jpeg" action=""
                                    :show-file-list="false" :http-request="handleUploadImg">
                                    <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" alt="商品主图" />
                                    <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
                                    <template #tip>
                                        <div class="el-upload__tip">
                                            上传的图片大小不能超过2M，支持jpg、png、jpeg格式
                                        </div>
                                    </template>
                                </el-upload>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="商品详情" prop="goodsDetail">
                                <!-- 富文本编辑器 -->
                                <Editor v-model="formData.goodsDetail" />
                            </el-form-item>
                        </el-row>
                    </el-form>
                </el-scrollbar>
                <el-row justify="center" class="mt20">
                    <el-button @click="close()">取消</el-button>
                    <el-button type="primary" @click="submitForm()">保存</el-button>
                </el-row>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import useForm from '@/hooks/useForm';
import { update, add, isExist } from '@/api/goods/list';
import { getCategoryList } from '@/api/goods/category';
import { defineAsyncComponent, ref, watch } from 'vue';
import { pinyin } from 'pinyin-pro';
import { isCode } from '@/utils/validate';
import { uploadImg } from '@/api/common/media';
import type { UploadRequestOptions } from 'element-plus';

// 引用编辑器组件
const Editor = defineAsyncComponent(() => import('@/components/editor/index.vue'))

const emit = defineEmits(['refresh'])

// 初始化数据
const initData = { status: 1, sort: 1 }
const {
    title, type, visible, loading, formData, oldFormData,
    formRef,
    open,
    close,
    submitForm
} = useForm({ initData, update, add }, emit)

// 导出父组件访问
defineExpose({ open })

// 分类下拉选项
const categoryOptions = ref<{
    categoryId: string;
    categoryName: string;
}[]>([])

watch(() => visible.value, (val) => {
    if (!val) return
    loadCategoryOptions()
})
// 加载分类下拉选项
async function loadCategoryOptions() {
    try {
        loading.value = true
        const { data } = await getCategoryList()
        categoryOptions.value = data || []
    } catch (error) {

    } finally {
        loading.value = false
    }
}

// 中文快捷码（中文拼音首字母）
function setQuickCode(name: string) {
    formData.value.quickCode =
        pinyin(name, { toneType: 'none', pattern: 'first', separator: '' }).toUpperCase()
}

// 校验商品编码是否存在
const codeValidator = async (rule: any, value: string, callback: any) => {
    if (!value) return callback(new Error('请输入商品编码'))
    if (!isCode(value)) return callback(new Error('商品编码只能是数字和字母'))
    if (oldFormData.value.code != value) {
        const { data } = await isExist({ code: value })
        if (data) return callback(new Error('商品编码已存在'))
    }
    callback()
}

// 上传图片
async function handleUploadImg(options: UploadRequestOptions) {
    try {
        loading.value = true
        const form = new FormData();
        form.append('file', options.file)
        // 其他数据转成json字符串传递给后台
        form.append('data', JSON.stringify({ sourceType: 'goods_img' }))
        // 开始上传
        const { data } = await uploadImg(form)
        formData.value.imageUrl = data
    } catch (error) {
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>